package com.example.aimultimodel.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author 18747
 */
@Configuration
public class AsyncConfig {

    @Bean(name = "toolExecutor") // 自定义线程池，专门处理工具调用
    public Executor toolExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 1. 核心线程数：根据CPU核数配置（如8核CPU设为8）
        executor.setCorePoolSize(8);
        // 2. 最大线程数：核心线程的2倍，应对突发请求
        executor.setMaxPoolSize(16);
        // 3. 队列容量：限制排队请求数，避免无界队列导致内存溢出
        executor.setQueueCapacity(50);
        // 4. 线程空闲时间：超过60秒销毁空闲线程
        executor.setKeepAliveSeconds(60);
        executor.setAwaitTerminationSeconds(60);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        // 5. 线程名前缀：方便日志排查
        executor.setThreadNamePrefix("ToolExecutor-");
        // 6. 拒绝策略：队列满时，直接抛出异常（避免静默失败）
        executor.setRejectedExecutionHandler((r, executor1) -> {
            throw new RuntimeException("工具调用线程池已满，请稍后再试");
        });
        executor.initialize();
        return executor;
    }
}
